#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
心理咨询师服务系统 - Flask应用主入口
"""

import os
from dotenv import load_dotenv

# 加载环境变量
basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env'))

from app import create_app, db
from app.models import (
    User, UserMembership, UserBasicInfo, UserAgreementConfirmation,
    Scale, ScaleCategory, ScalePublisher, ScaleQuestion, QuestionOption,
    ScaleScoringRule, ScoringRuleDimension, ScaleTag,
    Assessment, AssessmentAnswer, AssessmentScore,
    BasicInfoConfig, FieldOption, ValidationRule,
    AgreementContent, SystemConfig,
    AdminUser, AdminPermission,
    OperationLog, OperationLogData, ErrorLog, ErrorLogData
)
from config import config

# 创建应用实例
app = create_app(config[os.getenv('FLASK_ENV', 'development')])


@app.shell_context_processor
def make_shell_context():
    """Shell上下文处理器"""
    return {
        'db': db,
        'User': User,
        'UserMembership': UserMembership,
        'UserBasicInfo': UserBasicInfo,
        'UserAgreementConfirmation': UserAgreementConfirmation,
        'Scale': Scale,
        'ScaleCategory': ScaleCategory,
        'ScalePublisher': ScalePublisher,
        'ScaleQuestion': ScaleQuestion,
        'QuestionOption': QuestionOption,
        'ScaleScoringRule': ScaleScoringRule,
        'ScoringRuleDimension': ScoringRuleDimension,
        'ScaleTag': ScaleTag,
        'Assessment': Assessment,
        'AssessmentAnswer': AssessmentAnswer,
        'AssessmentScore': AssessmentScore,
        'BasicInfoConfig': BasicInfoConfig,
        'FieldOption': FieldOption,
        'ValidationRule': ValidationRule,
        'AgreementContent': AgreementContent,
        'SystemConfig': SystemConfig,
        'AdminUser': AdminUser,
        'AdminPermission': AdminPermission,
        'OperationLog': OperationLog,
        'OperationLogData': OperationLogData,
        'ErrorLog': ErrorLog,
        'ErrorLogData': ErrorLogData
    }


@app.cli.command()
def init_db():
    """初始化数据库"""
    db.create_all()
    print('数据库初始化完成')


@app.cli.command()
def create_admin():
    """创建管理员用户"""
    from werkzeug.security import generate_password_hash
    
    admin = AdminUser(
        username='admin',
        email='admin@psychology-system.com',
        password_hash=generate_password_hash('admin123'),
        is_active=True,
        is_super_admin=True
    )
    
    db.session.add(admin)
    db.session.commit()
    print('管理员用户创建完成: admin/admin123')


@app.cli.command()
def init_permissions():
    """初始化权限数据"""
    try:
        AdminPermission.create_default_permissions(db.session)
        print('权限数据初始化完成')
    except Exception as e:
        print(f'权限数据初始化失败: {str(e)}')
        db.session.rollback()


if __name__ == '__main__':
    app.run(
        host=os.getenv('FLASK_HOST', '0.0.0.0'),
        port=int(os.getenv('FLASK_PORT', 5000)),
        debug=True  # 强制启用调试模式
    )